import { NSpace, NTable, NPagination, NDatePicker,NCheckbox, NTreeSelect, NSelect  } from 'naive-ui'
import UserRoleSelector from './user-role-selector.vue'
//import RoleSelector from '../role/role-selector.vue'
import MetaHeader from '/src/components/vue-meta/meta-header.vue'

import uApi from '/src/api/base/u_api.js'
import roleApi from '/src/api/base/role_api.js'
import userApi from '/src/api/base/user-api'
import userRoleApi from '/src/api/base/user-role_api.js'
import globalStore from '/src/components/pinia/store.js'

import { parseTime } from '/src/utils/tools.js'
import const_data from '/src/utils/const-data.js'

const dialogForm = () => {
  return {
    id: null,
    name: null,
    username: null,
    password: null,
    status: null,
    // email: null,
  }
}

const statusOptions = () => {
  let keys = Object.keys(const_data.USER_STATUS)
  let opt = []
  for(let k=0; k<keys.length; k++) {
    let key = keys[k]
    opt.push({
      label: const_data.USER_STATUS[key],  value:key 
    })
  }
  //console.log(keys, opt)
  return opt
}
const statusSerachOptions = () => {
  let opt = statusOptions();
  //console.log(keys, opt)
  return [ {label: '全部', value: null} ].concat(opt)
}

export default {
  components: { NSpace, NTable, NPagination, NDatePicker, NCheckbox, NTreeSelect, NSelect,
    UserRoleSelector, MetaHeader },
  inject: [ "Message", "Dialog" ],
  setup() {    
    const store = globalStore()
    return {
      store
    }
  },
  props: {
    // 是否是从其他组件中调起此组件
    isModalComponent: { type: Boolean, default: ()=> false },
  },
  data() {
    return {
      datas: [],
      tableLoading: false,
      search: {
        name: null,
      },

      tableCheckList: {}, // 不是数组, key 是选中的下标, value 是否选中 
      tablePage: {
          page: 1,
          size: 10,
          total: 0,
      },

      // 弹出层
      showModal: false,
      isEdit: false,
      dialogFormSaving: false,
      dialogForm: dialogForm(),
      rules: {
          rules: {
              name: [ { required: true, message: '角色名字！',trigger: ['blur'] } ],
              roleCode: [ { required: true, message: '角色唯一代码',trigger: ['blur'] } ],
          }    
      },

      // 分页候选项
      pageSizeOption: [ {label: '10/页', value:10 }, {label: '20/页', value:20 }, {label: '30/页', value:30 } ],
      // pageSizeOption: [ {label: '1/页', value:1 }, {label: '2/页', value:2 }, {label: '3/页', value:3 } ]

      // 权限弹窗
      roleDialog: {
        visible: false,
        loading: false,
        saving: false,
        user: null, // 编辑的用户
        oldRoles: [], // 原来的角色  [{id,userId,role}]
      },

      // 重置密码弹窗
      resetPwd: {
        visible: false,
        saving: false,
        obj: null, // 用户对象
        password: null, // 新密码
      },
      resetPwdRules: {
        password: [ { required: true, message: '新密码呀！新密码！',trigger: ['blur'] } ],
      },

      statusOptions: statusOptions(),
      statusSerachOptions: statusSerachOptions(),
    }
  },
  computed: {
    // 表格全选状态
    tableAll() {
      let len = this.datas?.length
      if(len == 0){
        return false
      }
      for(let i=0; i<len; i++) {
        if(!this.tableCheckList[i]) {
          return false
        }
      }
      // 全选中
      return true
    },
    // 表格半选状态
    tableIndeterminate() {
      if(this.tableAll) {
        return false
      }

      let len = this.datas?.length
      for(let i=0; i<len; i++) {
        if(this.tableCheckList[i]) {
          return true
        }
      }
      // 全没选中
      return false
    },
  },
  created() {
    // this.datas = [
    //   { no: 1, code: 'Hello', description: '3:21' },
    //   { no: 2, code: 'Roll with It', description: '3:59' },
    // ]

    this.listData()
  }, 
  methods: {
    parseTime(datetimeStr, formatter) {
      return parseTime(new Date(datetimeStr), formatter)
    },
    userStatus(status) {
      return const_data.userStatus(status)
    },

    // ==弹窗==
    // 新增
    showAdd() {
      this.isEdit = false
      this.showModal = true
      this.dialogForm = dialogForm()
    },
    showEdit(obj) {
      this.isEdit = true
      this.showModal = true

      let cpObj = Object.assign({}, obj)
      cpObj.id = cpObj.id ? cpObj.id+"":null
      this.dialogForm = cpObj
    },
    showResetPwd(obj) {
      this.resetPwd.obj = obj
      this.resetPwd.visible = true
    },
    close() {
      this.showModal = false
    },
    reset() {
      this.dialogForm = dialogForm()
      this.dialogFormSaving = false
    },
    closeResetPwd() {
      this.resetPwd.visible = false
      this.resetPwd.obj = null
      this.resetPwd.saving = false
      this.resetPwd.password = null
    },

    // 页码变化
    pageChange(page) {
      // console.log("page", page)
      this.tablePage.page = page
      this.listData()
    },
    // 页大小变化
    pageSizeChange(pageSize) {
      // console.log("pageSize", pageSize)
      this.tablePage.page = 1
      this.tablePage.size = pageSize
      this.listData()
    },
    // 切换选中状态
    toggleCkeckAll() {
      // console.log("tableCheckList", this.tableAll, this.tableIndeterminate, this.tableCheckList)
      if(this.tableIndeterminate) { // 部分选 => 全选
          this.setCheckAll(true)
      } else if(this.tableAll) { // 全选 => 不选
          this.setCheckAll(false)
      } else { // 其他 => 全选
          this.setCheckAll(true)
      }
    },
    // 设置全选或取消全选
    setCheckAll(isCheck) {
      let len = this.datas?.length
      for(let i=0; i<len; i++) {
        this.tableCheckList[i] = isCheck
      }
    },
    listSelectedDatas() {
      let arr = []
      if(!this.datas) {
          return arr
      }

      let keys = Object.keys(this.tableCheckList)
      for(let i=0; i<keys.length; i++) {
          let key = keys[i]
          if(this.tableCheckList[key]) {
              arr.push(this.datas[key])
          }
      }

      return arr.filter(e => e)
    },

    // ==后台交互==
    saveVo() {
      this.$refs.dialogForm.validate((errors) => {
        if (!errors) {
          this.dialogFormSaving = true
          let data = Object.assign({}, this.dialogForm)
          userApi.addUser(data).then(res => {
            // console.log("saveVo", res)
            this.dialogFormSaving = false
            this.close()
            this.reset()
            this.Message.success( "添加成功", { closable: true, duration: 5000 } )
            this.listData()
          }, res => {
            this.dialogFormSaving = false
            this.Message.error( res.message, { closable: true, duration: 5000 } )
          })
        }
      })
    },
    updateVo() {
      this.$refs.dialogForm.validate((errors) => {
        if (!errors) {
          let data = Object.assign({}, this.dialogForm)
          userApi.updateUser(data).then(res => {
            //console.log("updateVo", res)
            this.close()
            this.reset()
            this.Message.success( "更新成功", { closable: true, duration: 5000 } )
            this.listData() // refresh
          }, res => {
            this.Message.error( res.message, { closable: true, duration: 5000 } )
          })
        }
      })
    },
    listData() {
      let data = {
        page: this.tablePage.page,
        size: this.tablePage.size,
        param: {
          name: this.search.name,
          username: this.search.name,
        }, // name 
      }
      this.tableLoading = true
      userApi.listUser(data).then( res => {
        // console.log("list", res)
        this.tableLoading = false
        this.tablePage.total = res.data.total
        let arrList =  res.data.list
        this.datas = arrList
        this.tableCheckList = {}
      }, err => {
        this.tableLoading = false
        this.Message.error( err.message, { closable: true, duration: 5000 } )
      })
    },
    deleteVo(vo) {
      this.Dialog.warning({
        title: '警告',
        content: '你确定要删除吗？',
        positiveText: '确定',
        negativeText: '不确定',
        onPositiveClick: () => {
          let data = {
              id: vo.id
          }
          userApi.delUser(data).then(res => {
              // console.log("updateVo", res)
              this.Message.success( "删除成功", { closable: true, duration: 5000 } )
              this.listData() // refresh
          }, res => {
              this.Message.error( res.message, { closable: true, duration: 5000 } )
          })
        }
      })
    },
    // 搜索模板选择
    searchData() {
      this.tablePage.page = 1
      this.listData()
    },
    saveChangePassword() {
      this.$refs.changePwdForm.validate((errors) => {
        if (!errors) {
          let data = {
            id: this.resetPwd.obj.id,
            password: this.resetPwd.password,
          }
          
          this.resetPwd.saving = true
          userApi.resetpwd(data).then(res => {
            this.resetPwd.saving = false
            this.Message.success( "密码重置成功", { closable: true, duration: 5000 } )
            this.closeResetPwd()
          }, res => {
            this.resetPwd.saving = false
            this.Message.error( res.message, { closable: true, duration: 5000 } )
          })
        }
      })
    },

    // ==角色部分==
    // 关闭角色权限视图
    closeRole() {
      this.roleDialog.user = null
      this.roleDialog.loading = false
      this.roleDialog.saving = false
      this.roleDialog.oldRoles = null
      this.roleDialog.visible = false
    },
    // 打开权限视图
    async editRole(user) {
      // console.log("user", user)
      const userCp = Object.assign({}, user)
      this.roleDialog.user = userCp
      // 获取用户的角色
      await userRoleApi.listUserAllRole({
        userId: userCp.id
      }).then(res => {
        let userRole = res.data  //  {user, roles: [{roleCode, name}]}
        this.roleDialog.oldRoles = userRole?.roles
      }, err => {
        this.Message.error( "用户角色查询失败", { closable: true, duration: 5000 } )
      })
      
      this.roleDialog.visible = true
      // 设置初始角色
      this.$nextTick(() => {
        this.$refs.roleSelector.setRoles(this.roleDialog.oldRoles)
      })
    },
    // 保存角色权限
    saveRole() {
      let roles = this.$refs.roleSelector.getRoles()
      // console.log("roles", roles)
      if(!roles) {
        return null
      }

      if(roles.length > 0) {
        this.__postSaveRole(this.roleDialog.user.id, roles)
      } else {
        this.Dialog.warning({
          title: '警告',
          content: '此用户没有任何权限！',
          positiveText: '删除所有权限',
          negativeText: '取消',
          onPositiveClick: () => {
            this.__postSaveRole(this.roleDialog.user.id, roles)
          }
        })
      }
      
    },
    // 后台发送保存请求
    __postSaveRole(userId, roles) {
      // roles :  [{roleCode, name}]
      const data = {
        user: { id:  userId} ,
        roles: roles
      }

      this.roleDialog.saving = true
      // 后端 redis 缓存会刷新。多机情况下，spring-security 的缓存清除不完全。建议重新登录
      userRoleApi.saveUserAllRole(data).then(res => { 
        this.roleDialog.saving = false
        this.Message.success( "保存成功", { closable: true, duration: 3000 } )
        this.closeRole()
      }, err => {
        this.roleDialog.saving = false
        let strMsg = err.message ? err.message : "用户角色查询失败"
        this.Message.error(strMsg, { closable: true, duration: 5000 } )
      })
    }
  },
}